package org.snail.activemq.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j;
import org.snail.attendence.bean.AliWorkDTO;
import org.snail.attendence.bean.AttendenceMongo;
import org.snail.attendence.mapper.AttendenceMongoMapper;
import org.snail.constant.ErrCodeConstant;
import org.snail.constant.MongoCollectionConstant;
import org.snail.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.Date;
import java.util.List;

@Component("attendenceListener")
@Log4j
public class AttendenceListener implements MessageListener {
    @Autowired
    private AttendenceMongoMapper attendenceMongoMapper;
    @Override
    public void onMessage(Message message) {
        log.info("[AttendenceListener.onMessage]:begin onMessage.");
        TextMessage textMessage = (TextMessage) message;
        try {
            //获取数据
            String jsonStr = textMessage.getText();
            Date insetTime = new Date();
            log.info("[AttendenceListener.onMessage]:receive message is,"+ jsonStr);
            if (jsonStr != null) {
                AttendenceMongo attendenceMongo = JSON.parseObject(jsonStr, AttendenceMongo.class);
                if (null == attendenceMongo || null == attendenceMongo.getAliWorkList() || attendenceMongo.getAliWorkList().isEmpty()){
                    log.error("activemq传值错误！list为空!");
                }
                List<AliWorkDTO> aliWorkDTOS = attendenceMongo.getAliWorkList();
                //在MongoDB中存入上次考勤记录，方便对比，先删除之前的在添加
                attendenceMongoMapper.dropCollection(MongoCollectionConstant.LAST_ATTENDENCE);
                attendenceMongoMapper.saveAttendenceList(aliWorkDTOS, MongoCollectionConstant.LAST_ATTENDENCE);
                try {
                    for (AliWorkDTO aliWorkDTO : aliWorkDTOS){
                        if (aliWorkDTO == null){
                            log.error("从考勤列表中遍历的对象为空！");
                            throw new CommonException(ErrCodeConstant.ILLEGAL_PARAM, "从考勤列表中遍历的对象为空！");
                        }
                        aliWorkDTO.setUploadTime(insetTime);
                        attendenceMongoMapper.saveAttendence(aliWorkDTO);
                    }
                } catch (CommonException e) {
                    log.error("mongoDB操作异常！", e);
                }
            }
        } catch (JMSException e) {
            log.error("[AttendenceListener.onMessage]:receive message(list wrap to DO) occured an exception",e);
        } catch (CommonException e) {
            log.error("存入临时考勤错误！", e);
        }
    }
}
